$(document).ready(function() {
    // Waiting until all js download, then show all content.
    $('#loading').hide();
    $('#accounts_menu').show();
    $('#accounts_content').show();

    // Get Transactions from Account
    $('#accounts ul a').click(function (e) {
        e.preventDefault();

        // Update new transaction link 
        $('#current_account').val(e.currentTarget.href);
        $('#current_account_id').val(e.currentTarget.id);

        $('#transaction_form form #account_id').val(e.currentTarget.href);
        // Disable the button temporarily
        //this.set('disabled', true);

        freshTransactionList(e.currentTarget.href);
    });

    // Fresh transaction list
    function freshTransactionList(url) {
        $("#main").mask("Waiting...");

        $.ajax({
            url: url,
            //dataType: 'json', // This attribute has a problem that if the data is a nested json format.
            timeout: 3000,
            success: function(data) {
                try {
                    var transactions;
                    var transactions_status;
                    transactions_status = $.toJSON(data);

                    $('.transaction_list').hide();
                    // Update Current Account
                    $('#accounts ul a').css('color', '#000');

                    if (transactions_status.length >= 1) {
                        for (var i in transactions_status) {
                            transaction_list = $.toJSON(transactions_status[i]);

                            transactions = $.toJSON(transaction_list.records);
                            updateTable(transactions, transaction_list);
                        }
                    }
                    else {
                        transactions = $.toJSON(transactions_status.records);
                        updateTable(transactions, transactions_status);
                        $('#accounts ul #' + "account_" + transactions_status.account_id).css('color', '#FF0000');
                    }
                }
                catch(e) {
                    alert(e);
                    //alert("Error updating transaction data");
                }
                finally {
                    //$('#account_{{ account.key.id }}').set('disabled',false);
                }

                $("#main").unmask();
            },
            error : function () {
                alert("Error getting transaction data");

                $("#main").unmask();
            }
        });
    };

    function updateTable(transactions, transactions_status) {

        var current_account_id = "account_" + transactions_status.account_id;
        var current_account = "/account/" + transactions_status.account_id + "/";

        transaction_list = $('#' + current_account_id + '_transaction_list');
        transaction_list.show();
        var tbl   = $('#' + current_account_id + '_transaction_list table'),
            html  = ["<tbody class='list'>"],i,j = 1,l,item;

        if (Number(transactions_status.count) != 0) {
            for (var i in transactions) {
                var transaction = transactions[i];
                var trans_id = transaction.transaction_id;

                if (i % 2 == 0)
                    html[j++] = '<tr class="even"><td>';
                else
                    html[j++] = '<tr class="odd"><td>';

                if (transaction.favorite === "True")
                    html[j++] = '<span><a id="' + trans_id + '_fav" class="delete" href="' + current_account + 'transaction/' + trans_id + '/favorite_off"><img src="/img/star_on.gif" /></a></span>';
                else
                    html[j++] = '<span><a id="' + trans_id + '_fav" class="delete" href="' + current_account + 'transaction/' + trans_id + '/favorite_on"><img src="/img/star_off.png" /></a></span>';
                html[j++] = '<label id="trans_' + trans_id + '_desc">' + transaction.description + '</label>';
                html[j++] = '<label id="trans_' + trans_id + '_account_id" style="display:none;">' + current_account + '</label>';
                html[j++] = '</td><td>';
                html[j++] = '<label id="trans_' + trans_id + '_amount">' + transaction.amount;
                html[j++] = '</td><td>';
                html[j++] = '<label id="trans_' + trans_id + '_is_income">' + transaction.is_income;
                html[j++] = '</td><td>';
                html[j++] = '<label id="trans_' + trans_id + '_tag">' + transaction.tag;
                html[j++] = '</td><td>';
                html[j++] = '<label id="trans_' + trans_id + '_date">' + transaction.transaction_date.substring(0, 10);
                html[j++] = '</td><td>';
                html[j++] = '<a id="' + trans_id + '" class="edit" href="#"><img src="/img/create_summary.gif" /></a>';
                html[j++] = '<span> </span>';
                html[j++] = '<a id="' + trans_id + '_delete" class="delete" href="' + current_account + 'transaction/' + trans_id + '/delete"><img src="/img/cross.gif" /></a>';
                html[j++] = '</td></tr>';
            }
        } else {
            html[j++] = '<tr><td colspan="6">No Inventory data</td></tr>';
        }
        html[j] = "</tbody>";
        $('#' + current_account_id + '_transaction_list table .list').replaceWith(html.join(''));
        // Update transaction list foot status
        var status_foot = '';
        var int_current_page = Number(transactions_status.current_page);
        var int_max_page = Number(transactions_status.max_page);
        if (int_current_page == 1) 
            status_foot += 'Previous Page';
        else
            status_foot += '<a href="' + current_account + 'transaction/list/page/' + String(int_current_page - 1) + '">Previous Page</a>';

        if (int_current_page == int_max_page || int_current_page > int_max_page)
            status_foot += 'Next Page';
        else
            status_foot += '<a href="' + current_account + 'transaction/list/page/' + String(int_current_page + 1) + '">Next Page</a>';

        status_foot += '<span>total count:' + transactions_status.count + '</span>';
        status_foot += '<span>total amount:' + transactions_status.transactions_amount + '</span>';

        a_node = $('#' + current_account_id + '_transaction_list table tfoot');

        $('#' + current_account_id + '_transaction_list table tfoot').replaceWith('<tfoot><tr><th colspan="6">'+status_foot+'</th></tr></tfoot>');
        // Update Account amount
        var account_node = $('#accounts ul #' + current_account_id + '_amount');
        account_node.html('(' + transactions_status.account_amount + ')');
        // Attach Page Event
        $('#' + current_account_id +'_transaction_list table tfoot tr th a').click(function (e) {
            e.preventDefault();
            freshTransactionList(e.currentTarget.href);
        });
        // Attach Delete Event
        $('#' + current_account_id + '_transaction_list table tbody tr td a.delete').click(function (e) {
            e.preventDefault();
            deleteTransaction(e);
        });
        // Attach Edit Event
        $('#' + current_account_id + '_transaction_list table tbody tr td a.edit').click(function (e) {
            e.preventDefault();

            $('#transaction_form form #description').val($("#trans_" + e.currentTarget.id + "_desc").html());
            $('#transaction_form form #amount').val($("#trans_" + e.currentTarget.id + "_amount").html());

            $('#transaction_form form input.is_income').each(function(){
                if ($(this).val() == $("#trans_" + e.currentTarget.id + "_is_income").html())
                    this.checked = true;
            });

            $('#transaction_form form #tag').val($("#trans_" + e.currentTarget.id + "_tag").html());
            $('#transaction_form form #transaction_date').val($("#trans_" + e.currentTarget.id + "_date").html());
            $('#transaction_form form #transaction_id').val(e.currentTarget.id);
            $('#transaction_form form #account_id').val($("#trans_" + e.currentTarget.id + "_account_id").html());

            transDialog();
        });

    };

    // Attach Create Transaction Event
    $('#create_trans').click(function (e) {
        e.preventDefault();

        transDialog();
    });

    function transDialog() {
        var execute = postTransaction; 
        var cancel = function() {
            $("#transaction_form").dialog("close");
        }
        
        var dialogOpts = {
            //autoOpen: false
            title: '<h1>Transaction Form</h1>',
            modal: true,
            buttons: {
                "Cancel": cancel,
                "Ok": execute
            }
        };
        
        $('#transaction_form').dialog(dialogOpts);
    }

    function postTransaction() {
        //var original_url = $('#current_account').get('value');
        var original_url = $('#transaction_form form #account_id').val();
        var request_url = original_url + "transaction/new";
        
        var trans_id = $('#transaction_form form #transaction_id').val();
        if (trans_id != "undefined" && trans_id.length > 0)
            request_url = original_url + "transaction/" + trans_id + "/edit";

        // Disable the button temporarily
        $('#transaction_form form #btn_commit').css('disabled', true);

        var data = '';
        data += 'description=' + $('#transaction_form form #description').val();
        data += '&amount=' + $('#transaction_form form #amount').val();


        var income_val = "";
        $('#transaction_form form input.is_income').each(function(){
                if (this.checked == true) 
                    income_val = $(this).val();
        });

        data += '&is_income=' + income_val;
        data += '&tag=' + $('#transaction_form form #tag').val();
        data += '&transaction_date=' + $('#transaction_form form #transaction_date').val();

        $.ajax({
            url: request_url,
            type: 'POST',
            data: data,
            timeout: 3000,
            success: function(res) {
                if (res == '200') {
                    $('#transaction_form form #transaction_id').val('');
                    $('#transaction_form form #description').val('');
                    $('#transaction_form form #amount').val('');
                    $('#transaction_form form #tag').val('');
                    //$('#transaction_form form #btn_commit').set('value', 'Submit');
                    //$('#transaction_form form #in').set('value', 'in');
                    //$('#transaction_form form #out').set('value', 'out');

                    url = $('#current_account').val(); // Might has problem here. If first use, the url is blank.

                    $("#transaction_form").dialog("close");
                    //$('#transaction_form').hide();

                    freshTransactionList(url);
                }
                else
                    alert("Can't create new transaction.");

                //$('#transaction_form form #btn_commit').css('disabled',false);
            },
            error: function () {
                alert("Error saving transaction data");
                //$('#transaction_form form #btn_commit').css('disabled',false);
            }
        });
    }

    // Attach tag event
    $('#tags ul a').click(function (e) {
        e.preventDefault();

        tag_id = e.currentTarget.id;
        // Update new transaction link 
        old_url = $('#current_account').val();
        // TODO: query all account by tag
        if (old_url == '') {
            old_url = '/account/transaction/list/';
        }

        if (old_url.indexOf("tag") !== -1)
            old_url = old_url.substring(0, old_url.indexOf("tag"));
        url = old_url + 'tag/' + tag_id + '/';

        $('#current_account').val(url);

        freshTransactionList(url);
    });

    // Attach favorite event
    $('#transaction_favorite').click(function (e) {
        e.preventDefault();

        // Update new transaction link 
        old_url = $('#current_account').val();
        // TODO: query all account by tag
        if (old_url == '') {
            old_url = '/account/transaction/list';
        }

        url = old_url + '?favorite=true';

        freshTransactionList(url);
    });

    // Attach date query event TODO need move it in furture
    $('#date_query').click(function (e) {

        // Update new transaction link 
        url = $('#current_account').val();
        // TODO: query all account by tag
        if (url === '') {
            url = '/account/transaction/list';
        }

        var min_date = $('#min_date').val();
        var max_date = $('#max_date').val();
        if (min_date !== '')
            url = url + '?min_date=' + min_date;
        if (max_date !== '')
            url = url + '&max_date=' + max_date; // TODO: Here is a bug

        freshTransactionList(url);
    });

    // Delete transaction
    function deleteTransaction(e) {
        $.ajax({
            url: e.currentTarget.href,
            timeout: 3000,
            success: function(res) {
                if (res == '200') {
                    url = $('#current_account').val();
                    freshTransactionList(url);
                }
                else 
                    alert("Error deleting transaction data");
            },
            error: function () {
                    alert("Error deleting transaction data");
            }
        });
    };

    $(function(){
        var pickerOpts = {
            showOn: "button",
            showOtherMonths: true,
            dateFormat:"yy-mm-dd"
        };
        
        $("#transaction_date").datepicker(pickerOpts);
    });
    
});

